package com.yixun.qfbao.util;

import com.yixun.qfbao.util.PorxyResult.HStatus;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.Map;


/**
 * 
 */
public class PorxyUtil {
	private static Logger log = Logger.getLogger(PorxyUtil.class);

	private static final int TimeoutInMilliseconds = 60000;

	/**
	 * post代理
	 */
	@SuppressWarnings("deprecation")
	public static PorxyResult postPorxy(Map<String, String> map, String serverAddr) {
		PorxyResult poxyResult = new PorxyResult();
		poxyResult.setStatus(HStatus.FAIL);
		String result = null;
		HttpClient client = new HttpClient();
		log.info("服务地址：" + serverAddr);
		PostMethod method = new PostMethod(serverAddr);
		method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
		for (String key : map.keySet()) {  
            method.addParameter(key, map.get(key));
			System.out.println(key + "," + map.get(key));
        }  
		//method.releaseConnection();
		try {
			client.setTimeout(TimeoutInMilliseconds);
			int status = client.executeMethod(method);
			result = method.getResponseBodyAsString();
			poxyResult.setContext(result);
			if (status == HttpStatus.SC_OK) {
				poxyResult.setStatus(HStatus.YES);
			}
			log.info("返回数据：" + result);
		} catch (HttpException e) {
			poxyResult.setStatus(HStatus.NETWORK);
			log.error("post请求错误：服务地址" + "服务地址＝" + serverAddr + ",服务参数＝" + map.toString() + "结果＝" + result);
		} catch (IOException e) {
			poxyResult.setStatus(HStatus.NETWORK);
			log.error("post请求错误：" + "服务地址＝" + serverAddr + ",服务参数＝" + map.toString() + "结果＝" + result);
		} finally {
			//method.releaseConnection();
			log.info("post请求完成：" + "服务地址＝" + serverAddr + ",服务参数＝" + map.toString() + "结果＝" + result);
			System.out.println("post请求完成：" + "服务地址＝" + serverAddr + ",服务参数＝" + map.toString() + "结果＝" + result);
		}
		return poxyResult;
	}

	/**
	 * get代理
	 */
	@SuppressWarnings("deprecation")
	public static PorxyResult getPorxy(String serverAddr) {
		PorxyResult poxyResult = new PorxyResult();
		poxyResult.setStatus(HStatus.FAIL);
		HttpClient client = new HttpClient();
		log.info("服务地址：" + serverAddr);
		GetMethod method = new GetMethod(serverAddr);
		String result = null;
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
		//method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
		// method.setParams(params);
		method.releaseConnection();
		try {
			client.setTimeout(TimeoutInMilliseconds);
			int status = client.executeMethod(method);
			//result = method.getResponseBodyAsString();
			result = new String(method.getResponseBody(), "utf-8");
			poxyResult.setContext(result);
			if (status == HttpStatus.SC_OK) {
				poxyResult.setStatus(HStatus.YES);
			}
			log.info("返回数据：" + result);
		} catch (HttpException e) {
			poxyResult.setStatus(HStatus.NETWORK);
			log.error("post请求错误：" + "服务地址＝" + serverAddr + "结果＝" + result);
		} catch (IOException e) {
			poxyResult.setStatus(HStatus.NETWORK);
			log.error("post请求错误：" + "服务地址＝" + serverAddr + "结果＝" + result);
		} finally {
			method.releaseConnection();
			log.info("post请求完成：" + "服务地址＝" + serverAddr + "结果＝" + result);
			System.out.println("post请求完成：" + "服务地址＝" + serverAddr + "结果＝"
					+ result);
		}
		return poxyResult;
	}

	public static void main(String[] args) {

		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx61e897b483dc0f3c&secret=2c3e226a2e593a44db51ef3e7a8ed7af";
		PorxyResult porxyResult = PorxyUtil.getPorxy(url);
	}

	@SuppressWarnings("deprecation")
	public static PorxyResult wxPostPorxy(String entityStr, String serverAddr) {
		PorxyResult poxyResult = new PorxyResult();
		poxyResult.setStatus(HStatus.FAIL);
		DefaultHttpClient client = new DefaultHttpClient();
		log.info("服务地址：" + serverAddr);
		String result = null;
//		PostMethod method = new PostMethod(serverAddr);
		try {
			HttpPost httpPost = new HttpPost(serverAddr);
			StringEntity entity = new StringEntity(entityStr, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			httpPost.setHeader("content-type", "application/json");
			CloseableHttpResponse httpResponse = client.execute(httpPost);
			result = EntityUtils.toString(httpResponse.getEntity());
			poxyResult.setContext(result);
			int status = httpResponse.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK) {
				poxyResult.setStatus(HStatus.YES);
			}
			log.info("返回数据：" + result);
		} catch (HttpException e) {
			poxyResult.setStatus(HStatus.NETWORK);
			log.error("post请求错误：" + "服务地址＝" + serverAddr + ",服务参数＝" + entityStr + "结果＝" + result);
		} catch (IOException e) {
			poxyResult.setStatus(HStatus.NETWORK);
			log.error("post请求错误：" + "服务地址＝" + serverAddr + ",服务参数＝" + entityStr + "结果＝" + result);
		} finally {
			//method.releaseConnection();
			log.info("post请求完成：" + "服务地址＝" + serverAddr + ",服务参数＝" + entityStr + "结果＝" + result);
			System.out.println("post请求完成：" + "服务地址＝" + serverAddr + ",服务参数＝" + entityStr + "结果＝" + result);
		}
		return poxyResult;
	}
}
